//
//  SelectedGoodNewViewController.m
//  HAODE
//
//  Created by LiYinDi on 16/3/22.
//  Copyright © 2016年 reabam.com. All rights reserved.
//

#import "SelectedGoodNewViewController.h"
#import "SelectedGoodNewHeaderDataModel.h"
#import "FMDB.h"
#import "PlaceOrderSpecTableViewCell.h"
#import "UIImageView+WebCache.h"
#import "specTableViewDataModel.h"


#import "WhsInAddViewController.h"

#import "BusinessOrderExtAddViewController.h"
//#import "NeedOrderAddViewController.h"

#import "NoSpecFmdbModel.h"
#import "NoSpecFmdbTool.h"

#import "HasSpecFmdbModel.h"
#import "HasSpecFmdbTool.h"
#import "LeftJoinFmdbModel.h"

@interface SelectedGoodNewViewController ()<PlaceOrderSpecCellDelegate>
{
    NSMutableArray *headerModelArray;
    
    NSString *userToken;
    NSInteger parentTag;
//    ReabamSingleton*commdity;
}
@property(nonatomic,strong)FMDatabase *userDB;
//@property(nonatomic,strong)FMDatabase *noSpecDB;
@end

@implementation SelectedGoodNewViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//    commdity=[ReabamSingleton shared];
    [self setNavigation];
    [self setAutoLayout];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    userToken = [user objectForKey:@"tokenId"];
    headerModelArray=[NSMutableArray array];
    
    //    [_totalCountView setBackgroundColor:[Global parseColor:@"#E01F3536"]];
    [self initDataBase];
    
    [self getTotalCountFromDB];
//    [self getTotalValue];
    
    CGFloat noSpectTotalMoney=[self getTotalMoneyFromNoSpecDB];
    CGFloat hasSpectTotalMoney=[self getTotalMoneyFromHasSpecDB];
    _totalLabel.text=[NSString stringWithFormat:@"%0.02f",noSpectTotalMoney+hasSpectTotalMoney];
    // Do any additional setup after loading the view from its nib.
}
-(void)initDataBase
{
//    NSString *dbPath = [self getDBPath];
//    NSLog(@"dbPath===%@",dbPath);
//    _userDB = [FMDatabase databaseWithPath:dbPath];
//    if (![_userDB open]) {
//        NSLog(@"open membersDB failed");
//        return;
//    }
    [self getNoSpecDataFromDB];
}

-(void)getTotalCountFromDB
{
    NoSpecFmdbModel *model=[NoSpecFmdbModel modalWith:userToken itemId:@"" itemCode:@"" imageUrlFull:@"" itemName:@"" maxPrice:@"" minPrice:@"" salePrice:@"" invQty:@"" specType:@"" specCount:@"" typeString:_typeString];
    NSString *resultStr=[NoSpecFmdbTool getCornerCount:model];
    _titleLabel.text=[NSString stringWithFormat:@"已选%@件商品",resultStr];
    
}
-(CGFloat)getTotalMoneyFromNoSpecDB
{
    CGFloat totalNoSpecMoney=0;
    //    PlaceOrderSubDataModel *model=modelArray[tag];
    NoSpecFmdbModel *model=[NoSpecFmdbModel modalWith:userToken itemId:@"" itemCode:@"" imageUrlFull:@"" itemName:@"" maxPrice:@"" minPrice:@"" salePrice:@"" invQty:@"" specType:@"" specCount:@"" typeString:_typeString];
    NSString *resultStr=[NoSpecFmdbTool getTotalNoSpecMoney:model];
    totalNoSpecMoney=resultStr.floatValue;
    return totalNoSpecMoney;
    
}
-(CGFloat)getTotalMoneyFromHasSpecDB
{
    CGFloat totalHasSpecMoney=0;
    HasSpecFmdbModel *model=[HasSpecFmdbModel modalWith:userToken itemId:@"" itemCode:@"" colorSpecID:@"" sizeSpecID:@"" specName:@"" specPrice:@"" specStock:@"" specCount:@"" typeString:_typeString specID:@""];
    NSString *resultStr=[HasSpecFmdbTool getTotalSpecMoney:model];
    totalHasSpecMoney=[resultStr floatValue];
    
    
    return totalHasSpecMoney;
    
}




-(void )getNoSpecDataFromDB
{
    NSString *sqlStr=[NSString stringWithFormat:@"SELECT * FROM t_NoSpec WHERE userToken = '%@' AND typeString = '%@' ;" ,userToken,_typeString];
    NSArray *array=[NoSpecFmdbTool queryData:sqlStr];
    //    NSLog(@"array>>>>--====%@",array);
    for (int i=0;i<array.count;i++) {
        NoSpecFmdbModel *fmModel=array[i];
        SelectedGoodNewHeaderDataModel *model=[[SelectedGoodNewHeaderDataModel alloc] init];
        
        model.imageUrlFull=fmModel.imageUrlFull;
        model.itemCode=fmModel.itemCode;
        model.itemId=fmModel.itemId;
        model.itemName=fmModel.itemName;
        model.maxPrice=fmModel.maxPrice;
        
        model.minPrice=fmModel.minPrice;
        model.salePrice=fmModel.salePrice;
        model.invQty=fmModel.invQty;
        
        model.specType=fmModel.specType;
        model.specCount=fmModel.specCount;
        model.isOpened = NO;
        
        [headerModelArray addObject:model];
        
    }

}
//-(NSString *)getDBPath
//{
//    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
//    NSString *DBPath = [documentPath stringByAppendingPathComponent:kUserDBNAME];
////    NSLog(@"DBPath//==%@",DBPath);
//    return DBPath;
//}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    SelectedGoodNewHeaderDataModel *headerModel=headerModelArray[section];
    
    
    if ([headerModel.specType intValue]!=0) {
        UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth,122)];
        [view setBackgroundColor:[UIColor whiteColor]];
        UIImageView *productImageView=[[UIImageView alloc] initWithFrame:CGRectMake(15, 20, 82, 82)];
        productImageView.layer.borderColor=[[UIColor colorWithRed:239.0f/255.0f green:239.0f/255.0f blue:239.0f/255.0f alpha:1] CGColor];
        productImageView.layer.borderWidth= 1.0f;
       
        [productImageView setImageWithURL:[NSURL URLWithString:headerModel.imageUrlFull]];
        [view addSubview:productImageView];
        
        UILabel *productNameLabel=[[UILabel alloc] initWithFrame:CGRectMake(109, 20, ScreenWidth-116, 18)];
        [productNameLabel setText:headerModel.itemName];
        productNameLabel.font=[UIFont systemFontOfSize:14];
        productNameLabel.textColor=[UIColor colorWithRed:51.0/255.0f green:51.0/255.0f  blue:51.0/255.0f  alpha:1.0];
        [view addSubview:productNameLabel];
        
        UILabel *productPriceLabel=[[UILabel alloc] initWithFrame:CGRectMake(109, 46, 200, 15)];
        [productPriceLabel setText:[NSString stringWithFormat:@"¥%0.02f",[headerModel.salePrice floatValue]]];
        productPriceLabel.font=[UIFont systemFontOfSize:12];
        productPriceLabel.textColor=[UIColor colorWithRed:102.0/255.0f green:102.0/255.0f  blue:102.0/255.0f  alpha:1.0];
        
        [view addSubview:productPriceLabel];
        
        UILabel *productInvLabel=[[UILabel alloc] initWithFrame:CGRectMake(ScreenWidth-122, 46,110, 15)];
        
        productInvLabel.font=[UIFont systemFontOfSize:12];
        productInvLabel.textColor=[UIColor colorWithRed:102.0/255.0f green:102.0/255.0f  blue:102.0/255.0f  alpha:1.0];
        NSString *str=[NSString stringWithFormat:@"库存 %d",[headerModel.invQty intValue]];
        NSMutableAttributedString *attriString = [[NSMutableAttributedString alloc] initWithString:str];
        [attriString addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:204.0/255.0 green:204.0/255.0 blue:204.0/255.0 alpha:1.0] range:NSMakeRange(0, 2)];
        
        productInvLabel.attributedText=attriString;
        
        productInvLabel.textAlignment=NSTextAlignmentRight;
        [view addSubview:productInvLabel];
        
        
        UILabel *productCountLabel=[[UILabel alloc] initWithFrame:CGRectMake(109, 85, 85, 15)];
        productCountLabel.font=[UIFont systemFontOfSize:14];
        productCountLabel.textColor=[UIColor colorWithRed:51.0/255.0f green:51.0/255.0f  blue:51.0/255.0f  alpha:1.0];
        
        //        [productCountLabel setText:];
        NSString *productCountStr=[NSString stringWithFormat:@"小计 %d",[headerModel.specCount intValue]];
        NSMutableAttributedString *productAttrIString = [[NSMutableAttributedString alloc] initWithString:productCountStr];
        [productAttrIString addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:153.0/255.0 green:153.0/255.0 blue:153.0/255.0 alpha:1.0] range:NSMakeRange(0, 2)];
        
        productCountLabel.attributedText=productAttrIString;
        productCountLabel.textAlignment=NSTextAlignmentLeft;
        [view addSubview:productCountLabel];
        
        UIButton *detailBtn=[UIButton buttonWithType:UIButtonTypeCustom];
        detailBtn.frame=CGRectMake(ScreenWidth-110, 72, 100, 30);
        detailBtn.layer.borderWidth=1.0;
        detailBtn.layer.borderColor=[UIColor colorWithRed:240.0/255.0f green:240.0/255.0f blue:240.0/255.0f alpha:240.0/255.0f].CGColor;
        detailBtn.tag=section;
         detailBtn.titleLabel.font = [UIFont systemFontOfSize: 14.0];
        if ( !headerModel.isOpened) {
            [detailBtn setImage:[UIImage imageNamed:@"zhankai"] forState:UIControlStateNormal];
        }
        else
        {
             [detailBtn setImage:[UIImage imageNamed:@"shouqi_shang"] forState:UIControlStateNormal];
        }
        
        [detailBtn setTitle:@"规格明细" forState: UIControlStateNormal];
        
        [detailBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -20, 0, 30)];
        [detailBtn setImageEdgeInsets:UIEdgeInsetsMake(0,68, 0, 0)];
        
       
        [detailBtn setTitleColor:[UIColor colorWithRed:90.0/255.0f green:130.0/255.0f blue:26.0f/255.0f alpha:1.0] forState:UIControlStateNormal];
        [detailBtn addTarget:self action:@selector(detaiBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        
        [view addSubview:detailBtn];
        UILabel *lineLabel=[[UILabel alloc] initWithFrame:CGRectMake(10,121,ScreenWidth-20,1)];
        if (!headerModel.isOpened) {
             lineLabel.backgroundColor=[UIColor colorWithRed:238.0/255.0f green:238.0/255.0f  blue:238.0/255.0f  alpha:1];
        }
        else
        {
             lineLabel.backgroundColor=[UIColor colorWithRed:250.0/255.0f green:250.0/255.0f  blue:250.0/255.0f  alpha:1];
        }
       
        
        [view addSubview:lineLabel];
        return view;
        
        
    }
    else {
        
        UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth,122)];
         [view setBackgroundColor:[UIColor whiteColor]];
        UIImageView *productImageView=[[UIImageView alloc] initWithFrame:CGRectMake(15, 20, 82, 82)];
        productImageView.layer.borderColor=[[UIColor colorWithRed:239.0f/255.0f green:239.0f/255.0f blue:239.0f/255.0f alpha:1] CGColor];
        productImageView.layer.borderWidth= 1.0f;
       
        [productImageView setImageWithURL:[NSURL URLWithString:headerModel.imageUrlFull]];
        [view addSubview:productImageView];
        
        UILabel *productNameLabel=[[UILabel alloc] initWithFrame:CGRectMake(109, 20, ScreenWidth-116, 18)];
        [productNameLabel setText:headerModel.itemName];
        productNameLabel.font=[UIFont systemFontOfSize:14];
        productNameLabel.textColor=[UIColor colorWithRed:51.0/255.0f green:51.0/255.0f  blue:51.0/255.0f  alpha:1.0];
        [view addSubview:productNameLabel];
        
        UILabel *productPriceLabel=[[UILabel alloc] initWithFrame:CGRectMake(109, 46, 200, 15)];
        [productPriceLabel setText:[NSString stringWithFormat:@"¥%0.02f",[headerModel.salePrice floatValue]]];
        productPriceLabel.font=[UIFont systemFontOfSize:12];
        productPriceLabel.textColor=[UIColor colorWithRed:102.0/255.0f green:102.0/255.0f  blue:102.0/255.0f  alpha:1.0];
        [view addSubview:productPriceLabel];
        
        
        UILabel *productInvLabel=[[UILabel alloc] initWithFrame:CGRectMake(ScreenWidth-122, 46, 110, 15)];
        //        [productInvLabel setText:[NSString stringWithFormat:@"库存 %d",[headerModel.invQty intValue]]];
        productInvLabel.font=[UIFont systemFontOfSize:12];
        productInvLabel.textColor=[UIColor colorWithRed:109.0/255.0f green:102.0/255.0f  blue:102.0/255.0f  alpha:1.0];
        NSString *str=[NSString stringWithFormat:@"库存 %d",[headerModel.invQty intValue]];
        NSMutableAttributedString *attriString = [[NSMutableAttributedString alloc] initWithString:str];
        [attriString addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:204.0/255.0 green:204.0/255.0 blue:204.0/255.0 alpha:1.0] range:NSMakeRange(0, 2)];
        
        productInvLabel.attributedText=attriString;
        productInvLabel.textAlignment=NSTextAlignmentRight;
        [view addSubview:productInvLabel];
        
        UIView *countParentView=[[UIView alloc] initWithFrame:CGRectMake(ScreenWidth-210, 68, 200, 34)];
        countParentView.layer.borderWidth=1.0;
        countParentView.layer.borderColor=[UIColor colorWithRed:240.0/255.0f green:240.0/255.0f blue:240.0/255.0f alpha:240.0/255.0f].CGColor;
        
        UIButton *subtractCountBtn=[UIButton buttonWithType:UIButtonTypeCustom];
        [subtractCountBtn setImage:[UIImage imageNamed:@"jian_hui.png"] forState:UIControlStateNormal];
        [subtractCountBtn setFrame:CGRectMake(0, 0, 34,34)];
        subtractCountBtn.tag=section;
        [subtractCountBtn addTarget:self action:@selector(noSpecSubtractCountBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [countParentView addSubview:subtractCountBtn];
        
        UITextField *noSpecCountTextfield=[[UITextField alloc] initWithFrame:CGRectMake(31, 0, 139, 34)];
        noSpecCountTextfield.text=[NSString stringWithFormat:@" %d",[headerModel.specCount intValue]];
        noSpecCountTextfield.textColor=[UIColor colorWithRed:21.0/255.0 green:25.0/255.0 blue:32.0/255.0 alpha:1.0f];
        noSpecCountTextfield.font=[UIFont systemFontOfSize:16];
        noSpecCountTextfield.textAlignment=NSTextAlignmentCenter;
        [countParentView addSubview:noSpecCountTextfield];
        
        UIButton *addCountBtn=[UIButton buttonWithType:UIButtonTypeCustom];
        addCountBtn.tag=section;
        [addCountBtn setImage:[UIImage imageNamed:@"jia.png"] forState:UIControlStateNormal];
        [addCountBtn setFrame:CGRectMake(160, 0, 34, 34)];
        [addCountBtn addTarget:self action:@selector(noSpecAddCountBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [countParentView addSubview:addCountBtn];
        
        [view addSubview:countParentView];
        UILabel *lineLabel=[[UILabel alloc] initWithFrame:CGRectMake(8,121,ScreenWidth-16,1)];
        
        lineLabel.backgroundColor=[UIColor colorWithRed:238.0/255.0f green:238.0/255.0f  blue:238.0/255.0f  alpha:1.0];
        
        [view addSubview:lineLabel];
        
        return view;
    }
    
}
-(void)detaiBtnClick:(UIButton *)sender
{
    parentTag=sender.tag;
    
    SelectedGoodNewHeaderDataModel *headerModel=headerModelArray[sender.tag];
    headerModel.isOpened = !headerModel.isOpened;
    headerModel.modelArray=[NSMutableArray arrayWithArray:[self getHasSpecDataFromDB:headerModel.itemId senderTag:sender.tag]];;
    [headerModelArray replaceObjectAtIndex:sender.tag withObject:headerModel];
    
    
    [_tableView reloadSections:[NSIndexSet indexSetWithIndex:sender.tag] withRowAnimation:UITableViewRowAnimationAutomatic];
   
    
}
-(NSArray * )getHasSpecDataFromDB:(NSString *)itemIdStr senderTag:(NSInteger)senderTag
{
    NSString *sqlStr=[NSString stringWithFormat:@"SELECT * FROM t_Spec WHERE userToken = '%@' AND itemID = '%@' AND typeString = '%@';" ,userToken,itemIdStr,_typeString];
    NSArray *fmArray=[HasSpecFmdbTool queryData:sqlStr];
    return fmArray;
}

-(void)noSpecSubtractCountBtnClick:(UIButton *)sender
{
    SelectedGoodNewHeaderDataModel *headerModel=headerModelArray[sender.tag];
    if (headerModel.specCount.intValue>1) {
        
        
        NSString *oriCount=[NSString stringWithFormat:@"%d",[headerModel.specCount intValue]];
        
        oriCount=[NSString stringWithFormat:@"%d",[oriCount intValue]-1];
        
        headerModel.specCount=oriCount;
        
        [headerModelArray replaceObjectAtIndex:sender.tag withObject:headerModel];
        
        [_tableView reloadSections:[NSIndexSet indexSetWithIndex:sender.tag] withRowAnimation:UITableViewRowAnimationFade];
        
//        [self updateNoSpecDBData:headerModel.itemId ifAdd:@"N"];
        NoSpecFmdbModel *noSpecmodel=[NoSpecFmdbModel modalWith:userToken itemId:headerModel.itemId itemCode:@"" imageUrlFull:@"" itemName:@"" maxPrice:@"" minPrice:@"" salePrice:@"" invQty:@"" specType:@"" specCount:headerModel.specCount typeString:_typeString];
        
        [NoSpecFmdbTool modifySpecCount:noSpecmodel];
    }
    
}
-(void)noSpecAddCountBtnClick:(UIButton *)sender
{
    SelectedGoodNewHeaderDataModel *headerModel=headerModelArray[sender.tag];
    if ([_typeString isEqualToString:@"WhsOut"]||[_typeString isEqualToString:@"PlaceOrder"]) {
        if ([headerModel.specCount  intValue]<[ headerModel.invQty intValue]) {
            NSString *oriCount=[NSString stringWithFormat:@"%d",[headerModel.specCount intValue]];
            oriCount=[NSString stringWithFormat:@"%d",[oriCount intValue]+1];
            headerModel.specCount=oriCount;
            [headerModelArray replaceObjectAtIndex:sender.tag withObject:headerModel];
            [_tableView reloadSections:[NSIndexSet indexSetWithIndex:sender.tag] withRowAnimation:UITableViewRowAnimationAutomatic];
            
            NoSpecFmdbModel *noSpecmodel=[NoSpecFmdbModel modalWith:userToken itemId:headerModel.itemId itemCode:@"" imageUrlFull:@"" itemName:@"" maxPrice:@"" minPrice:@"" salePrice:@"" invQty:@"" specType:@"" specCount:headerModel.specCount typeString:_typeString];
            
            [NoSpecFmdbTool modifySpecCount:noSpecmodel];
            
        }
        else
        {
            UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示" message:@"已超出产品库存量" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        }
    }
    else
    {
        
        NSString *oriCount=[NSString stringWithFormat:@"%d",[headerModel.specCount intValue]];
        oriCount=[NSString stringWithFormat:@"%d",[oriCount intValue]+1];
        headerModel.specCount=oriCount;
        [headerModelArray replaceObjectAtIndex:sender.tag withObject:headerModel];
        [_tableView reloadSections:[NSIndexSet indexSetWithIndex:sender.tag] withRowAnimation:UITableViewRowAnimationAutomatic];
        
        NoSpecFmdbModel *noSpecmodel=[NoSpecFmdbModel modalWith:userToken itemId:headerModel.itemId itemCode:@"" imageUrlFull:@"" itemName:@"" maxPrice:@"" minPrice:@"" salePrice:@"" invQty:@"" specType:@"" specCount:headerModel.specCount typeString:_typeString];
        
        [NoSpecFmdbTool modifySpecCount:noSpecmodel];
    }
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return headerModelArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    SelectedGoodNewHeaderDataModel *groupModel = headerModelArray[section];
    NSInteger count = groupModel.isOpened? groupModel.modelArray.count:0;
    return count;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * const  ResultTableViewCellIdentifier = @"PlaceOrderSpecTableViewCell";
    PlaceOrderSpecTableViewCell *cell=( PlaceOrderSpecTableViewCell *)[tableView dequeueReusableCellWithIdentifier: ResultTableViewCellIdentifier];
    if (cell==nil) {
        NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"PlaceOrderSpecTableViewCell" owner:self options:nil];
        cell = [array objectAtIndex:0];
    }
    cell.delegate=self;
     cell.parentIndex=indexPath.section;
    cell.addCountBtn.tag=indexPath.row;
    cell.subtractCountBtn.tag=indexPath.row;
    SelectedGoodNewHeaderDataModel *headerModel=headerModelArray[indexPath.section];
    
    specTableViewDataModel *model=headerModel.modelArray[indexPath.row];
    cell.nameLabel.text= model.specName;
    cell.contentLabel.text=[NSString stringWithFormat:@"¥%0.02f  库存%d",[model.specPrice floatValue],[model.specStock intValue]];
    cell.countTextField.text=[NSString stringWithFormat:@" %d", [model.specCount intValue]];
     [cell.lineLabel setBackgroundColor:[UIColor colorWithRed:250.0/255.0f green:250.0/255.0f  blue:250.0/255.0f  alpha:1.0]];
    if (indexPath.row==headerModel.modelArray.count-1) {
        [cell.lineLabel setBackgroundColor:[UIColor colorWithRed:238.0/255.0f green:238.0/255.0f  blue:238.0/255.0f  alpha:1.0]];
    }
    
    
    return cell;
}
#pragma mark PlaceOrderSpecTableViewCellDelegate
-(void)SpecCellAddCountBtnClick:(NSUInteger)tag parentIndex:(NSUInteger)parentIndex
{
    SelectedGoodNewHeaderDataModel *headerModel=headerModelArray[parentIndex];
    specTableViewDataModel *specModel=headerModel.modelArray[tag];
    
    HasSpecFmdbModel *model=[HasSpecFmdbModel modalWith:userToken itemId:headerModel.itemId itemCode:@"" colorSpecID:specModel.colorSpecID sizeSpecID:specModel.sizeSpecID specName:@"" specPrice:@"" specStock:@"" specCount:@"" typeString:_typeString specID:@""];
    if ([_typeString isEqualToString:@"WhsOut"]||[_typeString isEqualToString:@"PlaceOrder"]) {
        BOOL suc= [HasSpecFmdbTool modifySpecCountWithLimit:model countText:@"1"];
        if (suc) {
            NSString *oriCount=[NSString stringWithFormat:@"%d",[specModel.specCount intValue]];
            oriCount=[NSString stringWithFormat:@"%d",[oriCount intValue]+1];
            specModel.specCount=oriCount;
            [headerModel.modelArray replaceObjectAtIndex:tag withObject:specModel];
            
            headerModel.specCount=[NSString stringWithFormat:@"%d",[headerModel.specCount intValue]+1];
            //            NSLog(@"headerModel.specCount>>>>>>===%@",headerModel.specCount);
            [headerModelArray replaceObjectAtIndex:parentIndex withObject:headerModel];
            
            [self updateNoSpecCount:headerModel.itemId countStr:headerModel.specCount typeStr:_typeString];
            [self getTotalCountFromDB];
            
            CGFloat noSpectTotalMoney=[self getTotalMoneyFromNoSpecDB];
            CGFloat hasSpectTotalMoney=[self getTotalMoneyFromHasSpecDB];
            _totalLabel.text=[NSString stringWithFormat:@"%0.02f",noSpectTotalMoney+hasSpectTotalMoney];
            
            
            NSIndexPath *tmpIndexpath=[NSIndexPath indexPathForRow:tag inSection:parentIndex];
            [_tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:tmpIndexpath, nil]  withRowAnimation:UITableViewRowAnimationNone];
            [_tableView reloadSections:[NSIndexSet indexSetWithIndex:parentIndex] withRowAnimation:UITableViewRowAnimationNone];
            
        }
        else{
            UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示" message:@"已超商品库存量" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        }
        
    }
    else
    {
        BOOL suc= [HasSpecFmdbTool modifySpecCountNoLimit:model countText:@"1"];
        if (suc) {
            NSString *oriCount=[NSString stringWithFormat:@"%d",[specModel.specCount intValue]];
            oriCount=[NSString stringWithFormat:@"%d",[oriCount intValue]+1];
            specModel.specCount=oriCount;
            [headerModel.modelArray replaceObjectAtIndex:tag withObject:specModel];
            
            headerModel.specCount=[NSString stringWithFormat:@"%d",[headerModel.specCount intValue]+1];
            [headerModelArray replaceObjectAtIndex:parentIndex withObject:headerModel];
            
            [self updateNoSpecCount:headerModel.itemId countStr:headerModel.specCount typeStr:_typeString];
            [self getTotalCountFromDB];
            
            NSIndexPath *tmpIndexpath=[NSIndexPath indexPathForRow:tag inSection:parentIndex];
            [_tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:tmpIndexpath, nil]  withRowAnimation:UITableViewRowAnimationNone];
            [_tableView reloadSections:[NSIndexSet indexSetWithIndex:parentIndex] withRowAnimation:UITableViewRowAnimationNone];
        }
        
    }
}
-(void)updateNoSpecCount:(NSString *)itemID countStr:(NSString *)countStr typeStr:(NSString *)typeStr
{
    NoSpecFmdbModel *noSpecmodel=[NoSpecFmdbModel modalWith:userToken itemId:itemID itemCode:@"" imageUrlFull:@"" itemName:@"" maxPrice:@"" minPrice:@"" salePrice:@"" invQty:@"" specType:@"" specCount:countStr typeString:typeStr];
    
    //            [self updateHasSpecDBData:tag ifAdd:@"N"];
    [NoSpecFmdbTool modifySpecCount:noSpecmodel];
    
}

-(void)SpecCellSubtractCountBtnClick:(NSUInteger)tag parentIndex:(NSUInteger)parentIndex
{
    
    SelectedGoodNewHeaderDataModel *headerModel=headerModelArray[parentIndex];
    specTableViewDataModel *specModel=headerModel.modelArray[tag];
    
    NSString *oriCount=[NSString stringWithFormat:@"%d",[specModel.specCount intValue]];
    oriCount=[NSString stringWithFormat:@"%d",[oriCount intValue]-1];
    if ([oriCount intValue]>0) {
        HasSpecFmdbModel *model=[HasSpecFmdbModel modalWith:userToken itemId:headerModel.itemId itemCode:@"" colorSpecID:specModel.colorSpecID sizeSpecID:specModel.sizeSpecID specName:@"" specPrice:@"" specStock:@"" specCount:@"" typeString:_typeString specID:@""];
        
        BOOL suc= [HasSpecFmdbTool modifySpecCountNoLimit:model countText:@"-1"];
        if (suc) {
            specModel.specCount=oriCount;
            [headerModel.modelArray replaceObjectAtIndex:tag withObject:specModel];
            headerModel.specCount=[NSString stringWithFormat:@"%d",[headerModel.specCount intValue]-1];
            [headerModelArray replaceObjectAtIndex:parentIndex withObject:headerModel];
            
            [self updateNoSpecCount:headerModel.itemId countStr:headerModel.specCount typeStr:_typeString];
            [self getTotalCountFromDB];
            CGFloat noSpectTotalMoney=[self getTotalMoneyFromNoSpecDB];
            CGFloat hasSpectTotalMoney=[self getTotalMoneyFromHasSpecDB];
            _totalLabel.text=[NSString stringWithFormat:@"%0.02f",noSpectTotalMoney+hasSpectTotalMoney];
            
            NSIndexPath *tmpIndexpath=[NSIndexPath indexPathForRow:tag inSection:parentIndex];
            [_tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:tmpIndexpath, nil]  withRowAnimation:UITableViewRowAnimationNone];
            
            [_tableView reloadSections:[NSIndexSet indexSetWithIndex:parentIndex] withRowAnimation:UITableViewRowAnimationNone];
            
        }
    }
    else if ([oriCount intValue]==0){
        NSString *sqlStr=[NSString stringWithFormat:@"DELETE FROM t_Spec WHERE userToken = '%@' AND itemID = '%@' AND colorSpecID = '%@' AND sizeSpecID = '%@' AND typeString = '%@';",userToken, headerModel.itemId,specModel.colorSpecID,specModel.sizeSpecID,_typeString];
        [HasSpecFmdbTool deleteData:sqlStr];
        [headerModel.modelArray removeObjectAtIndex:tag];
        headerModel.specCount=[NSString stringWithFormat:@"%d",[headerModel.specCount intValue]-1];
        [headerModelArray replaceObjectAtIndex:parentIndex withObject:headerModel];
        
        [self updateNoSpecCount:headerModel.itemId countStr:headerModel.specCount typeStr:_typeString];
        [self getTotalCountFromDB];
        CGFloat noSpectTotalMoney=[self getTotalMoneyFromNoSpecDB];
        CGFloat hasSpectTotalMoney=[self getTotalMoneyFromHasSpecDB];
        _totalLabel.text=[NSString stringWithFormat:@"%0.02f",noSpectTotalMoney+hasSpectTotalMoney];
        
        NSIndexPath *tmpIndexpath=[NSIndexPath indexPathForRow:tag inSection:parentIndex];
        
        
        [_tableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:tmpIndexpath, nil] withRowAnimation:UITableViewRowAnimationNone];
        if ([headerModel.specCount intValue]==0) {
            NSString *deleteSqlStr=[NSString stringWithFormat:@"DELETE FROM t_NoSpec WHERE userToken = '%@' AND itemId = '%@' AND typeString = '%@' ;",userToken,headerModel.itemId,_typeString];
            [NoSpecFmdbTool deleteData:deleteSqlStr];
            
            [headerModelArray removeObjectAtIndex:parentIndex];
            [_tableView reloadData];
        }
    }
}

#pragma mark  -select cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 122;
}
-(void)setAutoLayout
{
    [_titleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left) ;
        make.right.equalTo(self.view.mas_right) ;
        make.height.equalTo(@40) ;
        make.top.equalTo(self.view.mas_top).with.offset(64);
    }];
    [_clearBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.right.equalTo(self.view.mas_right).with.offset(-10) ;
        make.height.equalTo(@40) ;
        make.width.equalTo(@30) ;
        make.top.equalTo(_titleView.mas_top) ;
    }];
    [_lastView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left) ;
        make.right.equalTo(_submitConfirmBtn.mas_left) ;
        make.height.equalTo(@48) ;
        make.bottom.equalTo(self.view.mas_bottom);

    }];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left)  ;
        make.right.equalTo(self.view.mas_right)   ;
        make.bottom.equalTo(_lastView.mas_top) ;
        make.top.equalTo(self.view.mas_top).with.offset(40);
    }];
    
    
    [_submitConfirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.right.equalTo(self.view.mas_right) ;
        make.width.equalTo(@160) ;
        make.height.equalTo(@48) ;
        make.bottom.equalTo(self.view.mas_bottom);
    }];
    [_totalCountView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left) ;
        make.right.equalTo(_submitConfirmBtn.mas_left) ;
        make.height.equalTo(@48) ;
        make.bottom.equalTo(self.view.mas_bottom);
    }];
    
}

- (IBAction)clearAllBtnClick:(id)sender {
    NSString *sqlStr1=[NSString stringWithFormat:@"DELETE FROM t_NoSpec WHERE userToken = '%@' AND typeString  = '%@'",userToken,_typeString];
    NSString *sqlStr2=[NSString stringWithFormat:@"DELETE FROM t_Spec WHERE userToken = '%@' AND typeString  = '%@'",userToken,_typeString];
    [NoSpecFmdbTool deleteData:sqlStr1];
    [HasSpecFmdbTool deleteData:sqlStr2];
    [headerModelArray removeAllObjects];
    [_tableView reloadData];

    _titleLabel.text=[NSString stringWithFormat:@"已选0件商品" ];
    _totalLabel.text=@"0.00";
}
- (IBAction)confirmBtnClick:(id)sender {
    NSArray *resultArray= [NoSpecFmdbTool queryLeftJoin:_typeString userToken:userToken];
    NSMutableArray *productImageArray=[NSMutableArray array];
    NSMutableArray *productIDArray=[NSMutableArray array];
    NSMutableArray *productItemCodeArray=[NSMutableArray array];
//    NSMutableArray *productItemTypeArray=[NSMutableArray array];
    NSMutableArray *productNameArray=[NSMutableArray array];
    NSMutableArray *productPriceArray=[NSMutableArray array];
    NSMutableArray *productCountArray=[NSMutableArray array];
    NSMutableArray *productSpecNameArray=[NSMutableArray array];
    NSMutableArray *productSpecIDArray=[NSMutableArray array];
    NSMutableArray *productSpecPriceArray=[NSMutableArray array];
    NSMutableArray *productStockCountArray=[NSMutableArray array];
    for (int i=0; i<resultArray.count; i++) {
        LeftJoinFmdbModel *model=resultArray[i];
        [productIDArray addObject:model.itemId];
        [productItemCodeArray addObject:model.itemCode];
        [productImageArray addObject:model.imageUrlFull];
        [productNameArray addObject:model.itemName];
        [productPriceArray addObject:model.salePrice];
        [productCountArray addObject:model.mainCount];
        [productSpecNameArray addObject:model.specName];
        [productSpecPriceArray addObject:model.specPrice];
        [productStockCountArray addObject:model.specCount];
        [productSpecIDArray addObject:model.specID];
    }

//   NSLog(@"productItemCodeArray==%@",productItemCodeArray);
//    commdity.userName=nil;
    //  shouyingViewController *shouyinVC=[[shouyingViewController alloc] init];／／1.0里面东西不管
    if (productItemCodeArray.count>0) {
        
        
        if ([self.typeString isEqualToString:@"Order"]) {
            
            BusinessOrderExtAddViewController *shouyinVC=[[BusinessOrderExtAddViewController alloc] init];//2.0{9个参数 少2个}
            shouyinVC.headImageFullArray=productImageArray;
            shouyinVC.itemCodeArray=productItemCodeArray;
            
            shouyinVC.specNameArray=productSpecNameArray;
            shouyinVC.itemIdArray= productIDArray;
            shouyinVC.itemNameArray=productNameArray;
            shouyinVC.specIdArray=productSpecIDArray;
            shouyinVC.dealPriceArray=productPriceArray;
            shouyinVC.quantityArray=productCountArray;
            shouyinVC.saveTypeStr=_typeString;
            
            NSLog(@"----%@",productImageArray);
            //  shouyinVC.TotalMoney=_totalLabel.text;//[NSString stringWithFormat:@"%0.02f",totalValue];
            [self.navigationController pushViewController:shouyinVC animated:YES];
            
            
        }
        
        if ([self.typeString isEqualToString:@"WhsOut"]) {
            WhsInAddViewController *detailViewController = [[WhsInAddViewController alloc] init];
            detailViewController.titleName=@"确认出库";
            detailViewController.Whs=@"WhsOut";
            detailViewController.Type=@"WhsOutType";
            detailViewController.saveTypeStr=self.typeString;
            detailViewController. itemCodeArray=productItemCodeArray;
            detailViewController. itemIdArray=productIDArray;
            detailViewController. itemNameArray=productNameArray;
            detailViewController. headImageFullArray=productImageArray;
            detailViewController. dealPriceArray=productPriceArray;
            detailViewController. specIdArray=productSpecIDArray;
            detailViewController. quantityArray=productCountArray;
            detailViewController. specNameArray=productSpecNameArray;
            [self.navigationController pushViewController:detailViewController animated:YES];
            
        }
        
        if ([self.typeString isEqualToString:@"WhsIn"]) {
            WhsInAddViewController *detailViewController = [[WhsInAddViewController alloc] init];
            detailViewController.titleName=@"确认入库";
            detailViewController.Whs=@"WhsIn";
            detailViewController.Type=@"WhsInType";
            detailViewController.saveTypeStr=self.typeString;
            detailViewController. itemCodeArray=productItemCodeArray;
            detailViewController. itemIdArray=productIDArray;
            detailViewController. itemNameArray=productNameArray;
            detailViewController. headImageFullArray=productImageArray;
            detailViewController. dealPriceArray=productPriceArray;
            detailViewController. specIdArray=productSpecIDArray;
            detailViewController. quantityArray=productCountArray;
            detailViewController. specNameArray=productSpecNameArray;
            
            [self.navigationController pushViewController:detailViewController animated:YES];
            
        }
        
        
        if ([self.typeString isEqualToString:@"CheckVouch"]) {
            
            WhsInAddViewController *detailViewController = [[WhsInAddViewController alloc] init];
            detailViewController.titleName=@"确认录入";
            detailViewController.Whs=@"CheckVouch";
            detailViewController.Type=@"CheckVoucType";
            detailViewController.saveTypeStr=self.typeString;
            detailViewController. itemCodeArray=productItemCodeArray;
            detailViewController. itemIdArray=productIDArray;
            detailViewController. itemNameArray=productNameArray;
            detailViewController. headImageFullArray=productImageArray;
            detailViewController. dealPriceArray=productPriceArray;
            detailViewController. specIdArray=productSpecIDArray;
            detailViewController. quantityArray=productCountArray;
            detailViewController. specNameArray=productSpecNameArray;
            
            [self.navigationController pushViewController:detailViewController animated:YES];
        }
        
        if ([self.typeString isEqualToString:@"Continue"]) {
            
            //            CheckVouchContinueViewController *detailViewController = [[CheckVouchContinueViewController alloc] init];
            //            detailViewController.titleName=@"继续盘点";
            //            detailViewController.Whs=@"Continue";
            //            detailViewController.ckvId=self.ckvId;
            //            detailViewController.ckvNo=self.ckvNo;
            //            detailViewController.whsName=self.whsName;
            //            detailViewController.itemTypeName=self.itemTypeName;
            //            detailViewController.whsId=self.whsId;
            //            detailViewController.itemTypeCode=self.itemTypeCode;
            //            detailViewController.saveTypeStr=self.Whs;
            //            [self.navigationController pushViewController:detailViewController animated:YES];
        }

            
        
        
    }
    else
    {
        UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:@"提示" message:@"您未选择商品" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alertView show];
    }
    
    
}

-(void)setNavigation
{
    [[self rdv_tabBarController] setTabBarHidden:YES];
    
    self.navigationController.navigationBarHidden=NO;
 
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    [[UINavigationBar appearance] setBarTintColor:Color];
    
    UIImage* backImage = [UIImage imageNamed:@"fanhui"];
    CGRect backframe = CGRectMake(0,0,30,30);
    UIButton* backButton= [[UIButton alloc] initWithFrame:backframe];
    [backButton setBackgroundImage:backImage forState:UIControlStateNormal];
    backButton.titleLabel.textAlignment=NSTextAlignmentLeft;
    [backButton addTarget:self action:@selector(BackAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
    UILabel* titleLabel=[[UILabel alloc]initWithFrame:CGRectMake(0, 0,40, 23)];
    titleLabel.text=@"已选商品";
    titleLabel.font=[UIFont systemFontOfSize: 19];
    self.navigationItem.titleView=titleLabel;
    self.navigationController.navigationBar.barStyle =UIBaselineAdjustmentNone ;
    UILabel *lineLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 43,ScreenWidth, 1)];
    [lineLabel setBackgroundColor:[UIColor colorWithRed:238.0/255.0 green:238.0/255.0 blue:238.0/255.0 alpha:1.0]];
    [self.navigationController.navigationBar addSubview:lineLabel];
    
}

-(void)BackAction:(UIButton *)sender{
    [self.navigationController popViewControllerAnimated:YES];
}

@end
